package com.cy.pj.notice.dao.impl;

import com.cy.pj.notice.dao.NoticeJdbcDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class NoticeJdbcDaoImpl implements NoticeJdbcDao {
    @Autowired
    private DataSource dataSource;

    @Override
    public void insert(Object[] objects) throws SQLException {
        Connection conn = dataSource.getConnection();
        String sql = "insert into sys_notices(title,content,type,status, createdTime,createdUser,modifiedTime,modifiedUser) values(?,?,?,?,?,?,?,?)";
        PreparedStatement stmt = conn.prepareStatement(sql);

        for (int i = 0; i <= 7; i++) {
            stmt.setObject(i+1,  objects[i]);
        }

//        stmt.setString(1, "开学通知");
//        stmt.setString(2, "2021年3月18号开学");
//        stmt.setString(3, "1");
//        stmt.setString(4, "0");
//        stmt.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
//        stmt.setString(6, "jason");
//        stmt.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
//        stmt.setString(8, "tony");

        stmt.execute();
        stmt.close();
        conn.close();
        System.out.println("insert ok");
    }

    @Override
    public List<Map<String, Object>> selectNotices(String sql,Object[] values) throws SQLException {
        Connection conn = dataSource.getConnection();
        PreparedStatement stmt = conn.prepareStatement(sql);
        for(int i=0;i<values.length;i++){
            stmt.setObject(i+1, values[i]);
        }
        boolean flag = stmt.execute();
        ResultSet rs = null;
        List<Map<String,Object>> list = new ArrayList<>();
        if (flag){
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()){
                Map<String,Object> map = new HashMap<>();
                for (int j = 1; j <= columnCount; j++) {
                    String columnLabel = rsmd.getColumnLabel(j);
                    map.put(columnLabel, rs.getObject(columnLabel));
                }
                list.add(map);
            }
        }
        rs.close();
        stmt.close();
        conn.close();
        return list;
    }
}
